package kr.saeildamil.androidstudty.ch19;

import kr.saeildamil.androidstudty.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class BackWork extends Activity {
	TextView mResult;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.ch19_backwork);
		setProgressBarIndeterminateVisibility(false);

		mResult = (TextView) findViewById(R.id.ch19_backwork_result);
	}

	public void mOnClick(View v) {
		new BackWorkAsyncTask().execute(0, 100);
	}

	class BackWorkAsyncTask extends AsyncTask<Integer, Integer, Integer> {
		boolean mQuit;
		ProgressDialog mProgress;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// setProgressBarIndeterminateVisibility(true);
			mProgress = new ProgressDialog(BackWork.this);
			// mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgress.setTitle("Calculating");
			mProgress.setMessage("Wait...");
			mProgress.setCancelable(false);
			mProgress.setProgress(0);
			mProgress.setButton("Cancel",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							mQuit = true;
							mProgress.dismiss();
						}
					});
			mProgress.show();
		}

		@Override
		protected Integer doInBackground(Integer... params) {
			int result = 0;
			for (int i = params[0]; i < params[1] + 1; i++) {
				result += i;
				publishProgress(result);
				try {
					Thread.sleep(200);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				if (mQuit) {
					return result;
				}
			}
			return result;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			mProgress.setProgress(values[0]);
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			mResult.setText(result + "");
			// setProgressBarIndeterminateVisibility(false);
			mProgress.dismiss();
			mQuit = false;
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
			// setProgressBarIndeterminateVisibility(false);
			mProgress.dismiss();
			mQuit = false;
		}

	}

}
